package cn.com.nes.site.module.dao.monitor;

import cn.com.nes.common.em.MmEnum;
import cn.com.nes.common.util.*;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.OtherData;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.FunctionDataDto;
import cn.com.nes.site.entity.dto.GroupDataDto;
import cn.com.nes.site.entity.dto.ResultCodeDto;
import cn.com.nes.site.entity.dto.WarningRuleDTO;
import cn.com.nes.site.kafka.KafkaTemplate;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.*;

@Repository
public class WarningDaoImpl extends BaseDaoImpl {

    public PageData ignore(DataReq req) throws SQLException {
        PageData res = new PageData();
        Connection conn = null;
        try
        {
            String manufactureId = req.getUinfo().getNes_companyId();
            String ignoredItem = (String) req.getReqData().get("ignoredItem");
            String sbId = (String) req.getReqData().get("sbId");
            String type = (String) req.getReqData().get("type");

            conn = DBUtils.getJdbcForOpe();
            StringBuffer sb = new StringBuffer();
            sb.append("insert into is_ignored_item (manufacture_id, type, ignored_item, sb_id) VALUES (?,?,?,?)  ");
            int result = this.update(conn, sb.toString(), new Object[]{manufactureId,type,ignoredItem,sbId});
            conn.commit();
            if (result > 0) {
                res.setRetCode(0);
                res.setRetMessage("OK");
            }else{
                return PageData.error("保存失败");
            }
        }catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            return PageData.error("保存失败");
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return res;
    }

    public PageData cancelIgnoredItem(DataReq req) throws SQLException {
        PageData res = new PageData();
        Connection conn = null;
        try
        {
            String manufactureId = req.getUinfo().getNes_companyId();
            String ignoredItem = (String) req.getReqData().get("ignoredItem");
            String sbId = (String) req.getReqData().get("sbId");
            String type = (String) req.getReqData().get("type");
            conn = DBUtils.getJdbcForOpe();
            StringBuffer sb = new StringBuffer();
            sb.append("delete from is_ignored_item  where ignored_item =? and type =? and sb_id =? and manufacture_id =? ");
            int result = this.update(conn, sb.toString(), new Object[]{ignoredItem,type,sbId,manufactureId});
            conn.commit();
            if (result > 0) {
                res.setRetCode(0);
                res.setRetMessage("OK");
            }else{
                return PageData.error("保存失败");
            }
        }catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            return PageData.error("保存失败");
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return res;
    }

    public PageData getWarningRules(DataReq req) throws SQLException {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("查询预警规则失败");
        Connection conn = null;
        StringBuffer sb = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();

            String areaCode = (String) req.getReqData().get("areaCode");
            String deviceType = (String) req.getReqData().get("deviceType");
            String deviceModel = (String) req.getReqData().get("deviceModel");
            String protocolId = (String) req.getReqData().get("protocolId");
            String companyId = req.getUinfo().getCompanyId();
            sb.append("select distinct a.name as ruleName, date_format(a.createTime, '%Y-%m-%d %T') as createTime, GROUP_CONCAT(b.sb_id) as sbids,count(b.sb_id) as deviceCount, " +
                    "d.xzqh, GROUP_CONCAT(d.xzqh)as xzqhdm, GROUP_CONCAT(t.xzqhmc) as xzqhmc, a.json, s.sblx_id as deviceModel, s.sbxh as deviceModelName, v.dic_no as deviceType, " +
                    " a.areaCode as edit_areaCode, a.deviceType as edit_deviceType, a.deviceModel as edit_deviceModel, a.protocolId as edit_protocolId, " +
                    "v.title as deviceTypeName, a.formula, a.scripts, p.protocol_id, a.rule_id as ruleId ");
            sb.append(" from warning_rules a inner join warning_rules_bind_devices b on a.rule_id = b.rule_id and b.deleted = 0");
            sb.append(" inner join nes_ope_prod.is_equipment_info c on c.sb_id = b.sb_id and c.sfsc = 0 ");
            sb.append(" inner join nes_ope_prod.is_install_info d on d.dd_id = c.dd_id and d.sfsc = 0 ");
            sb.append(" inner join nes_ope_prod.t_xzqh t on t.xzqhdm like concat(substr(d.xzqh, 1, 2),'%') and t.xzqhjb = 1");
            sb.append(" inner join nes_ope_prod.t_sblx s on s.sblx_id = c.sblx_id ");
            sb.append(" inner join nes_ope_prod.is_dict_value_info v on v.dic_no = s.sblx and type_id = 'd_type_2' ");
            sb.append(" inner join nes_ope_prod.is_wxsb w on w.wx_id = c.wx_id ");
            sb.append(" inner join nes_ope_prod.is_device_protocol_info p on p.protocol_id = w.protocol_id ");
            sb.append(" where a.deleted = 0 ");
            sb.append(StrUtil.isEmpty(protocolId) ? "" : " and p.protocol_id = '" + protocolId + "'");
            sb.append(StrUtil.isEmpty(areaCode) ? "" : " and t.xzqhdm = '" + areaCode + "'");
            sb.append(StrUtil.isEmpty(deviceType) ? "" : " and v.dic_no = '" + deviceType + "'");
            sb.append(StrUtil.isEmpty(deviceModel) ? "" : " and s.sbxh = '" + deviceModel + "'");
            sb.append(StrUtil.isEmpty(companyId) ? "" : " and a.company_id = '" + companyId + "'");
            sb.append("group by a.rule_id");
            sb.append(" order by a.createTime desc ");

            StringBuffer sbfrom = new StringBuffer();
            sbfrom.append(sb.toString());
            int idx = sbfrom.indexOf(" from ");
            sbfrom.delete(0, idx);
            Page page = new Page(conn, sbfrom.toString(), req.getPageid(), req.getPagesize(), res, new Object[]{});
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize());
            List<Map<String, Object>> list = this.queryForList(conn, sb.toString(), new Object[]{});

            for (Map<String, Object> map : list) {
                String json = (String) map.get("json");
                WarningRuleDTO warn = (WarningRuleDTO) JsonUtil.getObjFromStr(json, WarningRuleDTO.class);
                map.put("fields", warn.getFields());
                map.put("rules", warn.getRules());
                map.put("json", null);
                map.put("sbids", ((String) map.get("sbids")).split(","));
            }
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return res;
    }

    public PageData addWarningRules(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("新增预警规则失败");
        Connection conn = null;
        Connection conn_ope = null;
        List<Object> resList = new ArrayList<Object>();
        Map<String, Object> dateRes = new LinkedHashMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        StringBuffer sbope = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();
            conn_ope = DBUtils.getJdbcForOpe();
            String userid = req.getUinfo().getId();
            List<String> sbids = (List<String>) req.getReqData().get("sbids");
            // 查询当前配置预警规则的设备是否为同一协议，不相同，不能进行预警规则保存
            sb.append("select count(distinct c.protocol_id) from is_equipment_info a left join is_wxsb b on b.wx_id = a.wx_id left join is_device_protocol_info c on c.protocol_id = b.protocol_id where a.sb_id in (");
            for (int i = 0; i < sbids.size(); i++) {
                sb.append("'" + sbids.get(i) + "'");
                if (i < sbids.size() - 1) {
                    sb.append(",");
                }
            }
            sb.append(")");
            int protocolCount = this.queryForInt(conn_ope, sb.toString(), new Object[]{});
            if (protocolCount > 1) {
                res.setRetCode(9);
                res.setRetMessage("当前选中设备不是同一个协议，请选择相同协议的设备");
                return res;
            }

            String name = (String) req.getReqData().get("name");
            String protocolId = (String) req.getReqData().get("protocolId");
            String areaCode = (String) req.getReqData().get("areaCode");
            String deviceType = (String) req.getReqData().get("deviceType");
            String deviceModel = (String) req.getReqData().get("deviceModel");
            String formula = (String) req.getReqData().get("formula");
            String uuid = (String) req.getReqData().get("uuid");
            List<String> fields = (List<String>) req.getReqData().get("fields");
            List<String> unitValueName = (List<String>) req.getReqData().get("unitValueName");
            List<String> fieldstitle = (List<String>) req.getReqData().get("fieldstitle");
            List<String> operator = (List<String>) req.getReqData().get("operator");
            List<String> values = (List<String>) req.getReqData().get("values");
            List<String> connect = (List<String>) req.getReqData().get("connect");
            List<String> ids = (List<String>) req.getReqData().get("ids");
            String ruleId = "";

            // 生成预警规则数据
            StringBuffer fldList = new StringBuffer();
            String unitValueNameStr = "number";
            for (int i = 0; i < fields.size(); i++) {
                LinkedHashMap<String, String> e = new LinkedHashMap<String, String>();
                e.put("field", fields.get(i));
                e.put("title", fieldstitle.get(i));
                e.put("unitValueName", unitValueName.get(i));
                fldList.append(fields.get(i)).append(",");
                if (StrUtil.isEmpty(unitValueName.get(i))) {
                    unitValueNameStr = "string";
                }
                resList.add(e);
            }
            dateRes.put("fields", resList);
            dateRes.put("formula", formula);
            resList = new ArrayList<Object>();
            for (int i = 0; i < operator.size(); i++) {
                LinkedHashMap<String, String> e = new LinkedHashMap<String, String>();
                e.put("operator", operator.get(i));
                e.put("valuetype", unitValueNameStr);
                e.put("value", values.get(i));
                e.put("connect", connect.get(i));
                e.put("ids", ids.get(i));
                resList.add(e);
            }
            dateRes.put("rules", resList);
            //生成jsscripts
            StringBuffer scripts = new StringBuffer();
            for (int i = 0; i < resList.size(); i++) {
                String isChar = "";
                LinkedHashMap<String, String> item = (LinkedHashMap<String, String>) resList.get(i);
                if ("string".equals(item.get("valuetype"))) {
                    isChar = "'";
                }

                String connectStr = "";
                if (i < resList.size() - 1) {
                    if ("并且".equals(item.get("connect"))) {
                        connectStr = " && ";
                    } else if ("或".equals(item.get("connect"))) {
                        connectStr = " || ";
                    } else if ("=".equals(item.get("connect"))) {
                        connectStr = " = ";
                    }
                }
                scripts.append("(").append(formula).append(item.get("operator")).append(isChar).append(item.get("value")).append(isChar).append(") ").append(connectStr).append(" ");
            }
            dateRes.put("scripts", scripts.toString());
            Object obj = JSON.toJSON(dateRes);
            String json = obj.toString();

            long version = System.currentTimeMillis();

            sb.delete(0, sb.length());
            // 规则主表 新增/更新
            if (StrUtil.isEmpty(uuid)) {    // 新增
                ruleId = "AGENT_" + UuidUtils.generateUuid();
                sb.append("INSERT INTO `warning_rules`(`name`, `json`, `formula`, `fldList`, `scripts`, `deleted`, `version`, `createUid`, `modifyUid`, `protocolId`, `deviceModel`, `deviceType`, `areaCode`, `company_id`, `rule_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");
            } else {    // 编辑
                ruleId = uuid;
                sb.append("UPDATE warning_rules SET `name`=?, `json`=?, `formula`=?, `fldList`=?, `scripts`=?, `deleted`=?, `version`=?, `createUid`=?, `modifyUid`=?, `protocolId`=?, `deviceModel`=?, `deviceType`=?, `areaCode`=?, `company_id`=? WHERE `rule_id`=? ");
            }
            this.update(conn, sb.toString(), new Object[]{name, json, formula, fldList.toString(), scripts.toString(), 0, version, userid, userid, protocolId, deviceModel, deviceType, areaCode, req.getUinfo().getCompanyId(), ruleId});

            if (StrUtil.isNotEmpty(uuid)) {    // 编辑 先删除
                sb.delete(0, sb.length());
                sb.append("UPDATE warning_rules_bind_devices SET deleted = 1 where rule_id =?");
                this.update(conn, sb.toString(), new Object[]{ruleId});
                sbope.delete(0, sbope.length());
                sbope.append("UPDATE is_warningrules SET isdelete = 1 where applyUuid =?");
                this.update(conn_ope, sbope.toString(), new Object[]{ruleId});
            }
            // 规则设备表和运营规则表  新增/更新
            for (String sbid : sbids) {
                sb.delete(0, sb.length());
                sb.append("INSERT INTO warning_rules_bind_devices (rule_id, deleted, createUid, modifyUid, sb_id) VALUES (?,?,?,?,?)");
                this.update(conn, sb.toString(), new Object[]{ruleId, 0, userid, userid, sbid});
                sbope.delete(0, sbope.length());
                sbope.append("INSERT INTO nes_ope_prod.`is_warningrules`( `sb_id`, `name`,`fldList`, `scripts`, `json`, `isdelete`, `version`, `createUserID`, `lastUpdateUserID`, `uuid`, `applyUuid`) VALUES (?,?,?,?,?,?,?,?,?,?,?) ");
                this.update(conn_ope, sbope.toString(), new Object[]{sbid, name, fldList.toString(), scripts.toString(), json, 0, version, userid, userid, ("AGENT_" + UuidUtils.generateUuid()), ruleId});
                try {
                    KafkaTemplate.getInstance().sendMm(sbid, MmEnum.WarningRuleMm);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            res.setRetCode(0);
            res.setRetMessage("ok");
            conn.commit();
            conn_ope.commit();
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (conn_ope != null) {
                conn_ope.close();
            }
        }
        return res;
    }

    public PageData getDeviceAndItemForWarningRules(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取设备列表和数据项失败");
        Connection conn = null;
        Connection conn_ope = null;
        StringBuffer sb = new StringBuffer();
        Map<String, Object> data = new HashMap<>();
        try {
            conn_ope = DBUtils.getJdbcForOpe();
            conn = DBUtils.getJNDIDBConn();

            String areaCode = (String) req.getReqData().get("areaCode");
            String deviceType = (String) req.getReqData().get("deviceType");
            String deviceModel = (String) req.getReqData().get("deviceModel");
            String protocolId = (String) req.getReqData().get("protocolId");
            String keyWords = (String) req.getReqData().get("keyWords");
            String companyId = req.getUinfo().getCompanyId();


            sb.delete(0, sb.length());
            sb.append("select a.sb_id as deviceId, c.wx_id, if((a.alias is null or a.alias = ''), e.sbxh, a.alias) as deviceName, replace(b.xmdz, '　', '') as projectAddress,");
            sb.append(" b.xzqh, t.xzqhmc, e.sblx_id, e.sbxh,");
            sb.append(" d.protocol_id as protocolId, d.name as protocolName,date_format(a.cjsj, '%Y-%m-%d %T') as createTime, b.xmlxr, b.xmlxrdh");
            sb.append(" from is_equipment_info a");
            sb.append(" inner join is_install_info b on b.dd_id = a.dd_id and b.sfsc = 0");
            sb.append(" inner join t_xzqh t on t.xzqhdm = b.xzqh");
            sb.append(" inner join is_wxsb c on c.wx_id = a.wx_id and c.sfsc = 0");
            sb.append(" inner join is_device_protocol_info d on d.protocol_id = c.protocol_id and d.is_plc = 0 and is_deleted = 0");
            sb.append(" inner join t_sblx e on e.sblx_id = a.sblx_id");
            sb.append(" left join nes_ope_prod.is_norm_data_b ind on ind.dtu_id = a.wx_id and ind.sb_id = a.sb_id                                     ");
            sb.append(" left join nes_ope_prod.is_norm_data ind2 on ind2.dtu_id = a.wx_id and ind2.sb_id = a.sb_id ");
            sb.append(" where a.sfsc=0 ");
            String companyType = req.getUinfo().getCompanyType();
            if (!Globals.DEMO_COMPANYID.equals(req.getUinfo().getCompanyId())) {//不是演示账号
                if ("01".equals(companyType)) {//厂商
                    sb.append(" and a.manufacture_id= '").append(req.getUinfo().getNes_companyId()).append("' ");
                } else if ("02".equals(companyType)) {//代理商
                    sb.append(" and a.agent_id= '").append(req.getUinfo().getCompanyId()).append("' ");
                } else {//管理员
                    sb.append(" and (ind.is_online = 0 and ind2.gmt_create>DATE_ADD(now(),INTERVAL -60 MINUTE)) and a.manufacture_id='MA3NU7QX1' ");
                }
            } else {//演示账号默认德尚
                sb.append(" and (ind.is_online = 0 and ind2.gmt_create>DATE_ADD(now(),INTERVAL -60 MINUTE)) and a.manufacture_id='MA3NU7QX1' ");
            }
            sb.append(" and exists (select 1 from is_protocol_control_command ipcc where ipcc.is_deleted = 0 and ipcc.protocol_id = d.protocol_id)\n");
            sb.append(StrUtil.isEmpty(areaCode) ? "" : " and b.xzqh like concat('" + XzqhUtil.getQueryXzqh(conn_ope, areaCode) + "','%')");
            sb.append(StrUtil.isEmpty(deviceModel) ? "" : " and a.sblx_id = '" + deviceModel + "'");
            sb.append(StrUtil.isEmpty(protocolId) ? "" : " and d.protocol_id =  '" + protocolId + "'");
            sb.append(StrUtil.isEmpty(deviceType) ? "" : " and e.sblx = '" + deviceType + "'");
            sb.append(StrUtil.isEmpty(keyWords) ? "" : "and (b.xmlxr = '" + keyWords + "' or b.xmlxrdh = '" + keyWords + "')");
            List<Map<String, Object>> deviceList = this.queryForList(conn_ope, sb.toString(), new Object[]{});
            data.put("deviceList", deviceList);

            if (CollUtil.isNotEmpty(deviceList)) {
                String deviceId = (String) deviceList.get(0).get("deviceId");
                String wxid = (String) deviceList.get(0).get("wx_id");
                protocolId = StrUtil.isNotEmpty(protocolId) ? protocolId : (String) deviceList.get(0).get("protocolId");

                sb.delete(0, sb.length());
                sb.append("SELECT ");
                sb.append(" d.field_name AS dataItem, ");
                sb.append(" IF(c.fore_name != '', c.fore_name, c.name) dataName, ");
                sb.append(" c.classify AS classifyId, ");
                sb.append(" c.unit_value AS unitValueId, ");
                sb.append(" unitDict.title AS unitValueName, ");
                sb.append(" classifyDict.title AS classifyName, ");
                sb.append(" c.data_item_id AS dataItemId ");
                sb.append(" FROM ");
                sb.append(" nes_ope_prod.is_device_protocol_data_item_info c ");
                sb.append(" INNER JOIN nes_ope_prod.is_data_item_template_info d ON c.template_id=d.template_id and d.field_name not like 'temp%' ");
                sb.append(" AND d.is_deleted = 0 AND c.is_deleted = 0 ");
                sb.append(" INNER JOIN nes_ope_prod.is_equipment_info a ON a.protocol_id = c.protocol_id ");
//                sb.append(" INNER JOIN nes_ope_prod.is_device_item x on x.item_id = c.data_item_id  and x.is_deleted='0' ");
                sb.append(" LEFT JOIN nes_ope_prod.is_dict_value_info unitDict ON unitDict.type_id = 'd_type_28' AND unitDict.dic_no = c.unit_value AND unitDict.sfsc = 0 ");
                sb.append(" AND unitDict.sfty = 0 ");
                sb.append(" LEFT JOIN nes_ope_prod.is_dict_value_info classifyDict ON 'd_type_33' = classifyDict.type_id AND classifyDict.dic_no = c.classify ");
                sb.append(" AND classifyDict.manufacture_id = c.manufacture_id AND classifyDict.sfty = 0 AND classifyDict.sfsc = 0 ");
                sb.append(" WHERE ");
                sb.append("  a.sb_id = '").append(deviceId).append("' ");
                List<Map<String, Object>> itemList = this.queryForList(conn_ope, sb.toString(), new Object[]{});
                data.put("itemList", itemList);


                sb.delete(0, sb.length());
                sb.append(" SELECT ecp.field_name                             AS fieldName,\n" +
                        "               ecp.functionCode                           AS functionCode,\n" +
                        "               ecp.functionName                           AS functionName,\n" +
                        "               ecp.sblx_id                                AS sblxId,\n" +
                        "               ecp.functionType                           AS functionType,\n" +
                        "               ecp.`MaxValue`                             AS `MAXVALUE`,\n" +
                        "               ecp.`MinValue`                             AS `MinValue`,\n" +
                        "               ecp.groupCode                              AS groupCode,\n" +
                        "               IF(idvi2.title != '', idvi2.title, '基本参数') AS groupName,\n" +
                        "               ecp.list_val                               AS listVal,\n" +
                        "               idvi.title                                 AS unitValue,\n" +
                        "               ecp.protocol_id                            AS protocolId\n" +
                        "        FROM equipment_control_param ecp\n" +
                        "                     LEFT JOIN is_dict_value_info idvi ON ecp.unit_value = idvi.dic_no AND idvi.type_id = 'd_type_28'\n" +
                        "                     LEFT JOIN is_dict_value_info idvi2 on ecp.groupCode = idvi2.dic_no AND idvi2.type_id = 'd_type_33'\n" +
                        "                AND idvi2.manufacture_id = ecp.manufacture_id\n" +
                        "                WHERE ecp.sfsc = 0 and ecp.protocol_id = ?");
                List<Map<String, Object>> list = this.queryForList(conn_ope, sb.toString(), new Object[]{protocolId});
                if (CollUtil.isNotEmpty(list)) {
                    List<GroupDataDto> dto = new ArrayList<>();
                    String lastGroup = "default";
                    GroupDataDto groupDataDto = new GroupDataDto();
                    for (Map<String, Object> map : list) {
                        String groupCode = (String) map.get("groupCode");
                        if (!lastGroup.equals(groupCode)) {
                            groupDataDto = new GroupDataDto(groupCode, (String) map.get("groupName"));
                            dto.add(groupDataDto);
                        }
                        //格式化控制指令
                        FunctionDataDto functionData = formatControlCommand(deviceId, wxid, null, map, true);
                        if (StrUtil.isNotBlank(functionData.getFunctionCode())) {
                            groupDataDto.getFunctionData().add(functionData);
                        }
                        lastGroup = groupCode;
                    }

                    data.put("controlItemList", dto);
                } else {
                    data.put("controlItemList", null);
                }
            } else {
                data.put("itemList", null);
                data.put("controlItemList", null);
            }


            res.setData(data);
            res.setRetCode(0);
            res.setRetMessage("ok");
        } finally {
            if (conn_ope != null) {
                conn_ope.close();
            }
        }
        return res;
    }

    public FunctionDataDto formatControlCommand(String sbId, String wxId, List<HashMap<String, Object>> operationData,
                                                Map<String, Object> ecpi, boolean matchModeTemp) {
        FunctionDataDto functionDataDto = new FunctionDataDto();
        functionDataDto.setUnitValue((String) ecpi.get("unitValue"));
        functionDataDto.setFunctionCode((String) ecpi.get("functionCode"));
        functionDataDto.setFunctionName((String) ecpi.get("functionName"));
        functionDataDto.setFunctionType(Integer.valueOf((String) ecpi.get("functionType")));
        String fieldName = (String) ecpi.get("fieldName");
        functionDataDto.setField(fieldName);
        Integer funType = Integer.valueOf((String) ecpi.get("functionType"));
//        Object fieldValue = operationData.get(0).getOrDefault(fieldName, null);
        Integer rawValue = null;
//        functionDataDto.setMaxValue((Double) ecpi.get("MAXVALUE"), fieldValue);
//        functionDataDto.setMinValue((Double) ecpi.get("MinValue"), fieldValue);
        functionDataDto.setSblxId((String) ecpi.get("sblxId"));
        List<ResultCodeDto> listVal = JSONArray.parseArray((String) ecpi.get("listVal"), ResultCodeDto.class);
        String functionCode = functionDataDto.getFunctionCode();
        //存放所有命令名称
        Map<Integer, String> commandNames = new HashMap<>(listVal.size());
        //为listVal中的设定温度赋值
//        for (ResultCodeDto val : listVal) {
//            //获取当前模式名称
//            String field = val.getField();
//            try {
//                if (ObjectUtil.isNotNull(val.getOriginal_value())) {
//                    //当前的命令的采集原始值
//                    Integer originalVal = new BigDecimal(val.getOriginal_value()).intValue();
//                    //存一下所有命令名称, 原始值做key, 指令名做value
//                    String normalName = "";
//                    if ("02".equals(functionCode)) {
//                        BigDecimal normalValue = dataItemFieldMapper.getNormValue(wxId, sbId, originalVal);
//                        if (normalValue != null) {
//                            normalName = dataItemFieldMapper.getNormName(normalValue);
//                            val.setName(normalName);
//                            originalVal = normalValue.intValue();
//                        }
//                    }
//                    commandNames.put(originalVal, val.getName());
//                }
//            } catch (NumberFormatException f) {
//            }
//        }
        functionDataDto.setListVal(listVal);
//        try {
//            if (ObjectUtil.isNotNull(operationData.get(1).get(fieldName))) {
//                rawValue = new BigDecimal(operationData.get(1).get(fieldName).toString()).intValue();
//            }
//        } catch (NumberFormatException e) {
//        }
        //数值型或为空的类型直接赋值
//        if (ObjectUtil.isNotNull(fieldValue)) {
//            if (ObjectUtil.isNull(funType) || 3 == funType) {
//                functionDataDto.setFieldValue(fieldValue);
//            }
//            //如果是开关机指令, 含有开机字样的同一写为开机
//            else if ("01".equals(functionDataDto.getFunctionCode())) {
//                if (fieldValue.toString().matches(".*开机.*")) {
//                    functionDataDto.setFieldValue("开机");
//                } else {
//                    functionDataDto.setFieldValue("关机");
//                }
//            }
//            //如果采集值没有匹配上任何命令名称, 通过采集值匹配名称
//            else if (!commandNames.containsValue(fieldValue.toString()) && ObjectUtil.isNotNull(rawValue)) {
//                String commandName = commandNames.get(rawValue);
//                functionDataDto.setFieldValue(commandName);
//            } else {
//                functionDataDto.setFieldValue(fieldValue);
//            }
//            if (ObjectUtil.isNull(functionDataDto.getFieldValue())) {
//                functionDataDto.setFieldValue(fieldValue);
//            }
//        } else {
//            fieldValue = "01".equals(ecpi.get("functionCode"))
//                    ? "开机"
//                    : "02".equals(ecpi.get("functionCode"))
//                    ? functionDataDto.getListVal().get(0).getName()
//                    : fieldValue;
//            functionDataDto.setFieldValue(fieldValue);
//        }
        functionDataDto.setFieldValue("");
        return functionDataDto;
    }

    public PageData getQueryDataForWarningRules(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取查询条件数据失败");
        Connection conn = null;
        Connection conn_ope = null;
        StringBuffer sb = new StringBuffer();
        Map<String, Object> data = new HashMap<>();
        try {
            conn = DBUtils.getJNDIDBConn();
            conn_ope = DBUtils.getJdbcForOpe();

            // 查询运营厂商ID
            String companyId = req.getUinfo().getCompanyId();
            sb.append("SELECT nes_companyId,companyType from t_company where companyId='").append(companyId).append("' ");
            List<Map<String, Object>> companyList = this.queryForList(conn, sb.toString(), new Object[]{});
            if (CollUtil.isEmpty(companyList)) {
                res.setRetCode(9);
                res.setRetMessage("未查询到厂商信息");
                return res;
            }
            String manufactureId = (String) companyList.get(0).get("nes_companyId");
            String companyType=req.getUinfo().getCompanyType();
            if(!Globals.DEMO_COMPANYID.equals(req.getUinfo().getCompanyId())) {
                if(!"01".equals(companyType) || "02".equals(companyType)) {
                    manufactureId = "MA3NU7QX1";
                }
            } else {
                    manufactureId = "MA3NU7QX1";
            }

            // 查询协议数据
            sb.delete(0, sb.length());
            sb.append("select protocol_id, name from is_device_protocol_info where is_deleted = 0 and is_plc = 0 and manufacture_id=?");
            List<Map<String, Object>> protocolList = this.queryForList(conn_ope, sb.toString(), new Object[]{manufactureId});
            data.put("protocolList", protocolList);

            // 查询设备类型数据
            sb.delete(0, sb.length());
            sb.append("select value_id as id, dic_no as val, title as name from is_dict_value_info where sfsc = 0 and type_id = 'd_type_2' ");
            List<Map<String, Object>> deviceTypeList = this.queryForList(conn_ope, sb.toString(), new Object[]{});
            data.put("deviceTypeList", deviceTypeList);

            // 查询设备型号数据
            sb.delete(0, sb.length());
            sb.append("select sblx_id as modelId, sbxh as modelName from t_sblx where sfsc = 0 and manufacture_id=?");
            List<Map<String, Object>> deviceModelList = this.queryForList(conn_ope, sb.toString(), new Object[]{manufactureId});
            data.put("deviceModelList", deviceModelList);

            res.setData(data);
            res.setRetCode(0);
            res.setRetMessage("ok");
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (conn_ope != null) {
                conn_ope.close();
            }
        }
        return res;
    }

    public PageData deleteWarningRules(DataReq req) throws Exception {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("删除预警规则失败");
        Connection conn = null;
        Connection conn_ope = null;
        StringBuffer sb = new StringBuffer();
        try {
            conn = DBUtils.getJNDIDBConn();
            conn_ope = DBUtils.getJdbcForOpe();

            List<String> ruleIds = (List<String>) req.getReqData().get("ids");
            for (String ruleId : ruleIds) {
                // 删除预警主表
                sb.append("update warning_rules set deleted = 1 where rule_id=?");
                this.update(conn, sb.toString(), new Object[]{ruleId});

                // 删除预警设备
                sb.delete(0, sb.length());
                sb.append("update warning_rules_bind_devices set deleted = 1 where rule_id=?");
                this.update(conn, sb.toString(), new Object[]{ruleId});

                // 删除运营平台预警规则
                sb.delete(0, sb.length());
                sb.append("UPDATE is_warningrules SET isdelete = 1 where applyUuid =?");
                this.update(conn_ope, sb.toString(), new Object[]{ruleId});
            }
            res.setRetCode(0);
            res.setRetMessage("ok");
            conn.commit();
            conn_ope.commit();
        } finally {
            if (conn != null) {
                conn.close();
            }
            if (conn_ope != null) {
                conn_ope.close();
            }
        }
        return res;
    }

    public PageData getNewWarningList(DataReq req) {
        StringBuffer sb = new StringBuffer();
        StringBuffer sbfrom = new StringBuffer();
        PreparedStatement ps = null;
        ResultSet rs = null;
        PageData res = new PageData();
        Connection conn = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            //故障信息
            sb.delete(0, sb.length());
            sb.append(" SELECT ");
            sb.append(" distinct '主机' type,iii.xmlxr,concat(substr(iii.xmlxrdh,1,3),'****',substr(iii.xmlxrdh,8,4)) xmlxrdh, ");
            sb.append("	iei.sb_id, ");
            sb.append("	iei.alias, ");
            sb.append("	ind.warn_data_items, ");
            sb.append("	date_format( ind.gmt_create, '%T' ) gmt_create,concat(iii.xmdz,ifnull(iii.mph,'')) address, ");
            sb.append("	ind.other_data ");
            sb.append(" from nes_ope_prod.is_equipment_info iei  ");
//            sb.append(" INNER JOIN nes_ope_prod.is_equipment_warn_info iewi on iei.sb_id = iewi.sb_id ");
            sb.append(" INNER JOIN nes_ope_prod.is_norm_data ind ON iei.sb_id = ind.sb_id and is_warn = 1 ");
            sb.append(" inner join nes_ope_prod.t_sblx ts on iei.sblx_id = ts.sblx_id");
            sb.append(" left join nes_ope_prod.is_dict_value_info idvi on idvi.dic_no = ts.sblx and type_id = 'd_type_2' ");
            sb.append(" inner join nes_ope_prod.is_install_info iii on (iii.dd_id = iei.dd_id and iii.sfsc = 0) ");
            sb.append(" where iei.sfsc = 0 ");
            if (!StrUtil.isEmpty(req.getUinfo().getAreacode()))
                sb.append(XzqhUtil.getMultipleQueryXzqhConn(conn, req.getUinfo().getAreacode(), "iii.xzqh"));
            if (!StringUtils.isEmpty((String) req.getReqData().get("xzqhdm")) && !"86".equals((String) req.getReqData().get("xzqhdm")))
                sb.append(XzqhUtil.getMultipleQueryXzqhConn(conn, (String) req.getReqData().get("xzqhdm"), "iii.xzqh"));
            String companyType = req.getUinfo().getCompanyType();
            if ("01".equals(companyType)) {//厂商
                sb.append(" and iei.manufacture_id= '").append(req.getUinfo().getNes_companyId()).append("' ");
            } else if ("02".equals(companyType)) {//代理商
                sb.append(" and iei.agent_id= '").append(req.getUinfo().getCompanyId()).append("' ");
            }
            if (!StrUtil.isEmpty(((String) req.getReqData().get("sblx"))))
                sb.append(" and idvi.value_id = '").append(req.getReqData().get("sblx")).append("'");
            if (!StrUtil.isEmpty(((String) req.getReqData().get("sbxh"))))
                sb.append(" and ts.sblx_id = '").append(req.getReqData().get("sbxh")).append("'");

            if (!StrUtil.isEmpty(((String) req.getReqData().get("startTime")))) {
                sb.append(" and ind.gmt_create>=  '").append(req.getReqData().get("startTime")).append("' ");
            }

            if (!StrUtil.isEmpty(((String) req.getReqData().get("endTime")))) {
                sb.append(" and ind.gmt_create<=  '").append(req.getReqData().get("endTime")).append(" 23:59:59' ");
            }

            if (!StrUtil.isEmpty(((String) req.getReqData().get("erro_code")))) {
                sb.append(" and ind.fault_codes =  '").append(req.getReqData().get("erro_code")).append("' ");
            }

            sb.append(" and not EXISTS (SELECT 1 from warning_rules_bind_devices x where x.sb_id=iei.sb_id and x.deleted=0 and x.createUid='").append(req.getUinfo().getUuid()).append("' and x.createTime>DATE_ADD(now(),INTERVAL -60*2 MINUTE) ) ");

//            sb.append(" and ind.gmt_create>DATE_SUB(CURDATE(), INTERVAL 3 DAY)   ");
            sb = DBUitl.sql_check(sb);

            // 分页
            sbfrom.append(sb.toString());
            Page page1 = new Page(conn, " from (" + sbfrom.toString() + " ) tab", req.getPageid(), req.getPagesize(), res, null);
            sb.append(" ORDER BY gmt_create desc  ");
            sb.append(" limit ").append(page1.getOffsetlimit()).append(",").append(req.getPagesize());

            ps = conn.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            List<Map<String, Object>> page = new ArrayList<>();
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                for (int k = 1; k <= columnCount; k++) {
                    map.put(rsmd.getColumnLabel(k), rs.getObject(k));
                }
                page.add(map);
            }
            rs.close();
            ps.close();

            for (int i = 0; i < page.size(); i++) {
                HashMap<String, Object> map = (HashMap<String, Object>) page.get(i);
                String warn_data_items = (String) map.get("warn_data_items");
                Map<String, String> map_othersData = new HashMap<String, String>();
                String other_data = (String) map.get("other_data");
                other_data = ZipUtils.gunzip(other_data);
                List<OtherData> otherDataList = JSONArray.parseArray(
                        other_data, OtherData.class);
                //other_data省略这种会报空指针：[{"f": "a653", "s": "0", "v": "无"}, {"f": "a630", "s": "0", "v": "关"}, {"f": "a182", "s": "0", "v": "无"}, {"f": "a654", "s": "0", "v": "无"}, {"f": "a632", "s": "0", "v": "定流量"}, {"f": "a615", "s": "0", "v": "无"}, {"f": "a154", "s": "0", "v": "无"}, {"f": "a167", "s": "0", "v": "关"}, {"f": "a635", "s": "0", "v": "0"}, {"f": "a417", "s": "0", "v": "0"}, {"f": "a591", "s": "0", "v": "无"}, {"f": "a350", "s": "0", "v": "关机"}, {"f": "a415", "s": "0", "v": "0"}, {"f": "a617", "s": "0", "v": "无"}, {"f": "a162", "s": "0", "v": "无"}, {"f": "a588", "s": "0", "v": "无"}, {"f": "a636", "s": "0", "v": "0"}, {"f": "a619", "s": "0", "v": "无"}, {"f": "a641", "s": "0", "v": "0"}, {"f": "a624", "s": "0", "v": "禁用"}, {"f": "a163", "s": "0", "v": "无"}, {"f": "a173", "s": "0", "v": "无"}, {"f": "a169", "s": "0", "v": "无"}, {"f": "a149", "s": "0", "v": "无"}, {"f": "a626", "s": "0", "v": "禁用"}, {"f": "a609", "s": "0", "v": "无"}, {"f": "a622", "s": "0", "v": "0"}, {"f": "a183", "s": "0", "v": "无"}, {"f": "a614", "s": "0", "v": "无"}, {"f": "a627", "s": "0", "v": "关机"}, {"f": "a638", "s": "0", "v": "0"}, {"f": "a631", "s": "0", "v": "关"}, {"f": "a628", "s": "0", "v": "0"}, {"f": "a371", "s": "0", "v": "无"}, {"f": "a157", "s": "0", "v": "0"}, {"f": "a625", "s": "0", "v": "禁用"}, {"f": "a613", "s": "0", "v": "无"}, {"f": "a148", "s": "0", "v": "无"}, {"f": "a637", "s": "0", "v": "0"}, {"f": "a623", "s": "0", "v": "不启用"}, {"f": "a634", "s": "0", "v": "无"}, {"f": "a616", "s": "0", "v": "无"}, {"f": "a368", "s": "0", "v": "无"}, {"f": "a618", "s": "0", "v": "无"}, {"f": "a139", "s": "0", "v": "无"}, {"f": "a633", "s": "0", "v": "无"}, {"f": "a640", "s": "0", "v": "无"}, {"f": "a620", "s": "0", "v": "无"}, {"f": "a373", "s": "0", "v": "无"}, {"f": "a580", "s": "0", "v": "0"}, {"f": "a592", "s": "0", "v": "无"}, {"f": "a189", "s": "0", "v": "0"}, {"f": "a370", "s": "0", "v": "无"}, {"f": "a142", "s": "0", "v": "0"}, {"f": "a639", "s": "0", "v": "0"}, {"f": "a147", "s": "0", "v": "无"}, {"f": "a621", "s": "0", "v": "0"}, {"f": "a612", "s": "0", "v": "所有机组均无故障"}, {"f": "a422", "s": "0", "v": "禁用"}, {"f": "a190", "s": "0", "v": "不做处理"}, {"f": "a407", "s": "0", "v": "制冷"}, {"f": "a629", "s": "0", "v": "0"}, {"f": "a351", "s": "0", "v": "制冷"}]
                if(otherDataList!=null){
                for (OtherData otherData : otherDataList) {
                    map_othersData.put(otherData.getF(), otherData.getS());
                }}
                map.put("other_data", null);
                if (!StrUtil.isEmpty(warn_data_items)) {
                    Map<String, String> warnMap = JSON.parseObject(warn_data_items, Map.class);
                    for (Map.Entry<String, String> entry : warnMap.entrySet()) {
                        String data_item_id = entry.getKey();
                        String val = entry.getValue();
                        sb.delete(0, sb.length());
                       // sb.append(" SELECT rule_id,`name`,formula,scripts,json from warning_rules where rule_id='").append(data_item_id).append("' ");
                        sb.append("select wr.rule_id,wr.name,wr.formula,wr.scripts,wr.json from warning_rules wr inner join is_warningrules iw " +
                                "on iw.applyUuid=wr.rule_id where iw.uuid='").append(data_item_id).append("' ");
                        ps = conn.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                        rs = ps.executeQuery();
                        if (rs.next()) {
                            String json = rs.getString("json");
                            String scripts = rs.getString("scripts");
                            StringBuffer sbInfo1 = new StringBuffer();

                            WarningRuleDTO warn = (WarningRuleDTO) JsonUtil.getObjFromStr(json, WarningRuleDTO.class);
                            for (int m = 0; m < warn.getFields().size(); m++) {
                                Map<String, Object> item = warn.getFields().get(m);
                                scripts = scripts.replaceAll((String) item.get("field"), (String) item.get("title"));
                                sbInfo1.append(item.get("title")).append("=").append(map_othersData.get((String) item.get("field"))).append(";");
                            }

                            sb.delete(0, sb.length());
                            sb.append("预警规则：").append(scripts).append(",当前采集值：").append(sbInfo1.toString());
                            if (StrUtil.isEmpty(((String) map.get("fault_codes")))) {
                                map.put("fault_codes", sb.toString());
                            } else {
                                sb.insert(0, map.get("fault_codes"));
                                map.put("fault_codes", sb.toString());
                            }

                            map.put("ruleId", data_item_id);
                        } else {
                            map.put("fault_codes", "预警规则:无，当前采集值：无");
                            map.put("ruleId", data_item_id);
                        }
                        rs.close();
                        ps.close();
                    }
                }

            }

            res.setPage(page);
            res.setRetCode(0);
            res.setRetMessage("OK");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

        }
        return res;
    }


    /**
     * 查询预警发送列表
     *
     * @param req
     * @return
     */
    public PageData getWarningInfoList(DataReq req) {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("查询预警发送列表失败");
        Map<String, Object> param = req.getReqData();
        StringBuffer sb = new StringBuffer();
        StringBuffer sbfrom = new StringBuffer();
        Connection conn = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            String xzqhdm = (String) param.get("xzqhdm");
            String sblx = (String) param.get("sblx");
            String sbxh = (String) param.get("sbxh");
            String companyId = req.getUinfo().getCompanyId();

            sb.delete(0, sb.length());
            sb.append(" select ws.uuid,ws.sendWay_dx,ws.sendWay_app,ws.sendWay_gzh,ws.sendWay_xcx,date_format(ws.startTime,'%Y-%m-%d %H:%i:%s') as startTime,date_format(ws.endTime,'%Y-%m-%d %H:%i:%s') as endTime,count(iei.sb_id) as deviceCount,group_concat(iei.sb_id) as sbids,idp.protocol_id,idp.name as protocolName ");
            sb.append(" from warning_send ws ");
            sb.append(" left join warning_send_devices wsd ON ws.uuid = wsd.warninguuid and wsd.isdelete=0 ");
            sb.append(" left join nes_ope_prod.is_equipment_info iei ON wsd.sb_id = iei.sb_id ");//设备
            sb.append(" left join nes_ope_prod.t_sblx ts ON ( ts.sblx_id = iei.sblx_id AND ts.sfsc = 0 ) ");
            sb.append(" left join nes_ope_prod.is_dict_value_info v ON v.dic_no = ts.sblx AND type_id = 'd_type_2' ");
            sb.append(" left join nes_ope_prod.is_install_info iii ON ( iii.dd_id = iei.dd_id AND iii.sfsc = 0 ) ");
            sb.append(" left join nes_ope_prod.is_wxsb iw on iw.wx_id = iei.wx_id ");
            sb.append(" left join nes_ope_prod.is_device_protocol_info idp on idp.protocol_id = iw.protocol_id ");
            sb.append(" where 1 = 1 and ws.isdelete = 0 ");
            sb.append(XzqhUtil.getMultipleQueryXzqhConn(conn, req.getUinfo().getAreacode(), "iii.xzqh"));
            if (StringUtils.isNotEmpty(xzqhdm) && !"86".equals(xzqhdm)) {
                sb.append(XzqhUtil.getMultipleQueryXzqhConn(conn, xzqhdm, "iii.xzqh"));
            }
            if (StringUtils.isNotEmpty(sblx)) {
                sb.append(" and v.value_id = '").append(sblx).append("'");
            }
            if (StringUtils.isNotEmpty(sbxh)) {
                sb.append(" and ts.sblx_id = '").append(sbxh).append("'");
            }
            if (StringUtils.isNotEmpty(companyId)) {
                sb.append(" and ws.company_id = '").append(companyId).append("'");
            }
            sb.append(" GROUP BY ws.uuid ");
            sb.append(" order by ws.createTime desc ");
            sbfrom.append(sb.toString());
            int idx = sbfrom.indexOf(" from ");
            sbfrom.delete(0, idx);
            Page page1 = new Page(conn, sbfrom.toString(), req.getPageid(), req.getPagesize(), res, null);
            sb.append(" limit ").append(page1.getOffsetlimit()).append(",").append(req.getPagesize());
            List<Map<String, Object>> pageList = this.queryForList(conn, sb.toString(), new Object[]{});

            if (pageList != null && pageList.size() > 0) {
                sbfrom.delete(0, sbfrom.length());
                sbfrom.append(" select a.id ids, a.username,a.phone from warning_send_detalis a where a.warninguuid = ? and a.isdelete = 0 ");
                for (Map<String, Object> map : pageList) {
                    //设备详细信息
                    List deviceInfoList = new ArrayList();
                    String sbids = ((String) map.get("sbids"));
                    if (StringUtils.isNotEmpty(sbids)) {
                        String[] split = sbids.split(",");
                        sb.delete(0, sb.length());
                        sb.append(" SELECT iei.sb_id as deviceId,ts.sbxh AS deviceModel,v.title AS deviceTypeName,ifnull( tx.xzqhmc, '未知地区' ) xzqhmc,tx.xzqhdm,idp.protocol_id,idp.name as protocolName,iii.xmlxr,iii.xmlxrdh,if((iei.alias is null or iei.alias = ''), ts.sbxh, iei.alias) as deviceName,replace(iii.xmdz, '　', '') as projectAddress");
                        sb.append(" from nes_ope_prod.is_equipment_info iei ");
                        sb.append(" left join nes_ope_prod.t_sblx ts on ( ts.sblx_id = iei.sblx_id AND ts.sfsc = 0 ) ");
                        sb.append(" LEFT JOIN nes_ope_prod.is_dict_value_info v ON v.dic_no = ts.sblx AND type_id = 'd_type_2' ");
                        sb.append(" left JOIN nes_ope_prod.is_install_info iii ON ( iii.dd_id = iei.dd_id AND iii.sfsc = 0 ) ");
                        sb.append(" LEFT JOIN nes_ope_prod.t_xzqh tx ON tx.xzqhdm = iii.xzqh ");
                        sb.append(" left join nes_ope_prod.is_wxsb iw on iw.wx_id = iei.wx_id ");
                        sb.append(" left join nes_ope_prod.is_device_protocol_info idp on idp.protocol_id = iw.protocol_id ");
                        sb.append(" where 1=1 AND iei.sfsc = 0 and iei.sb_id= ? ");
                        for (String sb_id : split) {
                            List<Map<String, Object>> objList = this.queryForList(conn, sb.toString(), new Object[]{sb_id});
                            deviceInfoList.add(objList.get(0));
                        }
                    }
                    map.put("deviceInfo", deviceInfoList);

                    //用户详细信息
                    List<Map<String, Object>> detailInfoList = this.queryForList(conn, sbfrom.toString(), new Object[]{String.valueOf(map.get("uuid"))});
                    map.put("detailInfoCount", detailInfoList.size());
                    map.put("detailInfo", detailInfoList);
                }
            }
            res.setPage(pageList);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return res;
    }

    public PageData addWarningInfo(DataReq req) throws SQLException {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("ERROR");
        Map<String, Object> param = req.getReqData();
        StringBuffer sb = new StringBuffer();
        PreparedStatement ps = null;
        Connection conn = null;
        Connection conn_ope = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            conn_ope = DBUtils.getJdbcForOpe();
            String userid = req.getUinfo().getId();
            String uuid = (String) param.get("uuid");
            List<String> sbids = (List<String>) param.get("sbids");
            if (sbids == null || sbids.size() == 0) {
                res.setRetMessage("设备id不能为空！！！");
                return res;
            }
            // 查询当前配置预警发送规则的设备是否为同一协议，不相同，不能进行保存
            sb.append("select count(distinct c.protocol_id) from is_equipment_info a left join is_wxsb b on b.wx_id = a.wx_id left join is_device_protocol_info c on c.protocol_id = b.protocol_id where a.sb_id in (");
            for (int i = 0; i < sbids.size(); i++) {
                sb.append("'" + sbids.get(i) + "'");
                if (i < sbids.size() - 1) {
                    sb.append(",");
                }
            }
            sb.append(")");
            int protocolCount = this.queryForInt(conn_ope, sb.toString(), new Object[]{});
            if (protocolCount > 1) {
                res.setRetMessage("当前选中设备不是同一个协议，请选择相同协议的设备");
                return res;
            }

            String startTime = (String) param.get("startTime");
            String endTime = (String) param.get("endTime");
            String sendWay_gzh = String.valueOf(param.get("sendWay_gzh"));
            String sendWay_xcx = String.valueOf(param.get("sendWay_xcx"));
            String sendWay_dx = String.valueOf(param.get("sendWay_dx"));
            String sendWay_app = String.valueOf(param.get("sendWay_app"));

            List<String> ids = (List<String>) param.get("ids");
            List<String> username = (List<String>) param.get("username");
            List<String> phone = (List<String>) param.get("phone");

            String warningUuid = "";
            if (StrUtil.isEmpty(uuid)) {    // 新增
                warningUuid = "HEAT_" + UuidUtils.generateUuid();
                sb.delete(0, sb.length());
                sb.append(" INSERT INTO warning_send  (`sendWay_dx`, `sendWay_xcx`, `sendWay_gzh`, `sendWay_app`, `startTime`, `endTime`, `createUserID`, `createTime`, `company_id`, uuid) ");
                sb.append(" VALUES(?, ?, ?, ?, ?, ?, ?, now(),?, ?) ");
            } else {//修改
                warningUuid = uuid;
                sb.delete(0, sb.length());
                sb.append(" UPDATE warning_send ");
                sb.append(" SET `sendWay_dx` = ?, `sendWay_xcx` = ?, `sendWay_gzh` = ?, `sendWay_app` = ?, `startTime` = ?, `endTime` = ?,`lastUpdateUserID` = ?, `lastUpdateTime` =  now(), `company_id`=?  where uuid = ?");
            }
            this.update(conn, sb.toString(), new Object[]{sendWay_dx, sendWay_xcx, sendWay_gzh, sendWay_app, startTime, endTime, req.getUinfo().getUuid(), req.getUinfo().getCompanyId(), warningUuid});

            //预警发送设备
            if (StrUtil.isNotEmpty(uuid)) {    // 编辑 先删除
                sb.delete(0, sb.length());
                sb.append("UPDATE warning_send_devices SET isdelete = 1 where warninguuid =?");
                this.update(conn, sb.toString(), new Object[]{warningUuid});
            }
            if (sbids != null && sbids.size() > 0) {
                sb.delete(0, sb.length());
                sb.append(" insert into warning_send_devices (warninguuid, sb_id, createUid, createTime) values (?, ?, ?, now()) ");
                ps = conn.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                for (int i = 0; i < sbids.size(); i++) {
                    ps.setString(1, warningUuid);
                    ps.setString(2, sbids.get(i));
                    ps.setString(3, userid);
                    ps.addBatch();
                }
                ps.executeBatch();
            }
            //预警发送详细信息（客户）
            if (StrUtil.isNotEmpty(uuid)) {    // 编辑 先删除
                sb.delete(0, sb.length());
                sb.append("UPDATE warning_send_detalis SET isdelete = 1 where warninguuid =?");
                this.update(conn, sb.toString(), new Object[]{warningUuid});
            }
            if (ids != null && ids.size() > 0) {
                sb.delete(0, sb.length());
                sb.append(" insert into warning_send_detalis (id, warninguuid, username, phone, createUserID, createTime) values (?, ?, ?, ?, ?, now()) ");
                ps = conn.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                for (int i = 0; i < ids.size(); i++) {
                    ps.setString(1, ids.get(i));
                    ps.setString(2, warningUuid);
                    ps.setString(3, username.get(i));
                    ps.setString(4, phone.get(i));
                    ps.setString(5, userid);
                    ps.addBatch();
                }
                ps.executeBatch();
            }
            conn.commit();
            conn_ope.commit();
            res.setRetCode(0);
            res.setRetMessage("OK");
        } finally {
            if (conn != null) conn.close();
            if (conn_ope != null) conn_ope.close();
            if (ps != null) ps.close();
        }
        return res;
    }

    public PageData delWarningInfo(DataReq req) throws SQLException {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("ERROR");
        StringBuffer sb = new StringBuffer();
        Connection conn = null;
        try {
            conn = DBUtils.getJNDIDBConn();
            String uuid = (String) req.getReqData().get("uuid");
            if (StringUtils.isEmpty(uuid)) {
                res.setRetMessage("uuid不能为空");
                return res;
            }
            //删除设置对象
            sb.delete(0, sb.length());
            sb.append(" update warning_send_detalis set isdelete = 1 where warninguuid = ? ");
            this.update(conn, sb.toString(), new Object[]{uuid});
            sb.delete(0, sb.length());
            sb.append(" update warning_send set isdelete = 1 where uuid = ? ");
            this.update(conn, sb.toString(), new Object[]{uuid});
            sb.delete(0, sb.length());
            sb.append(" update warning_send_devices set isdelete = 1 where warninguuid = ? ");
            this.update(conn, sb.toString(), new Object[]{uuid});
            conn.commit();
            res.setRetCode(0);
            res.setRetMessage("OK");
            return res;
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }
}
